<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加商品分类按钮 -->
      <el-button type="primary" @click="addCate">添加分类</el-button>
      <!-- 商品分类列表 -->
      <tree-table
        :data="goodsCateList"
        border
        :columns="column"
        :show-row-hover="false"
        :selection-type="false"
        :expand-type="false"
        show-index
        class="margin"
      >
        <template slot="deleted" slot-scope="scope">
          <i class="el-icon-success success" v-if="!scope.row.cat_deleted"></i>
          <i class="el-icon-error error" v-else></i>
        </template>
        <template slot-scope="scope" slot="level">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag v-if="scope.row.cat_level === 1" type="success">二级</el-tag>
          <el-tag v-if="scope.row.cat_level === 2" type="warning">三级</el-tag>
        </template>
        <template slot="active" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="editCateName(scope.row)"
          >编辑</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteGoods(scope.row)"
          >删除</el-button>
        </template>
      </tree-table>
      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClose"
    >
      <!-- 添加分类表单 -->
      <el-form ref="addCateForm" :model="addCateForm" :rules="addCateFormRules" label-width="100px">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：">
          <el-cascader
            v-model="selectedKeys"
            :options="parentsCate"
            :props="{ expandTrigger: 'hover' ,value:'cat_id',label:'cat_name',checkStrictly: true}"
            :clearable="true"
            @change="selectedParentChange"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subAddCateForm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类名称-->
    <el-dialog
      title="编辑分类名称"
      :visible.sync="editCateDialogVisible"
      width="50%"
      @close="editCateDialogClose"
    >
      <el-form
        ref="editCateForm"
        :model="editCateForm"
        :rules="editCateFormRules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subEditForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表数组
      goodsCateList: [],
      queryInfo: {
        type: 3,
        // 当前页码值
        pagenum: 1,
        // 每页显示多少条数据
        pagesize: 5
      },
      //  总数据条数
      total: 0,
      //   树形网状表格的列属性配置
      column: [
        {
          prop: 'cat_name',
          label: '分类名称'
        },
        {
          prop: 'cat_deleted',
          label: '是否有效',
          //   表示该列作为模板列
          type: 'template',
          //   模板的名称
          template: 'deleted'
        },
        {
          prop: 'cat_level',
          label: '排序',
          //   表示该列作为模板列
          type: 'template',
          //   模板的名称
          template: 'level'
        },
        {
          label: '操作',
          width: '300px',
          //   表示该列作为模板列
          type: 'template',
          //   模板的名称
          template: 'active'
        }
      ],
      //   添加分类🔑
      addCateDialogVisible: false,
      //   分类表单
      addCateForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
      },
      //   分类表单验证规则
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请填写分类名称', trigger: 'blur' },
          {
            min: 2,
            max: 6,
            message: '分类名称应该在2~6个字符之间',
            trigger: 'blur'
          }
        ]
      },
      //   获取所有父级分类
      parentsCate: [],
      //   级联选择器中选中的父级分类id
      selectedKeys: [],
      //   控制编辑对话框的显示与隐藏
      editCateDialogVisible: false,
      //   编辑分类名称表单
      editCateForm: {},
      //   编辑分类表单验证规则
      editCateFormRules: {
        cat_name: [
          {
            required: true,
            message: '请填写要修改的分类名称',
            trigger: 'change'
          },
          {
            min: 2,
            max: 8,
            message: '分类名称的长度应该在2~8个字符之间',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created() {
    this.getGoodsCate()
  },
  methods: {
    // 获取商品分类列表
    async getGoodsCate() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类列表失败')
      }
      this.goodsCateList = res.data.result
      this.total = res.data.total
    },
    // pageSize改变时触发
    handleSizeChange(val) {
      this.queryInfo.pagesize = val
      this.getGoodsCate()
    },
    // 当前页改变时触发
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getGoodsCate()
    },
    // 点击添加分类按钮时触发
    addCate() {
      this.addCateDialogVisible = true
      this.getParentCateList()
    },
    // 关闭添加分类对话框
    addCateDialogClose() {
      this.$refs.addCateForm.resetFields()
      this.selectedKeys = []
      this.addCateForm.cat_level = 0
      this.addCateForm.cat_pid = 0
    },
    // 获取所有父级分类
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类失败')
      }
      this.parentsCate = res.data
    },
    // 当级联选择器中选中的父级分类发生改变时触发的函数
    selectedParentChange() {
      //   当selectedKeys数组长度大于0时，代表用户没有选择父级分类
      //  反之，选择了父级分类
      if (this.selectedKeys.length > 0) {
        this.addCateForm.cat_pid = this.selectedKeys[
          this.selectedKeys.length - 1
        ]
        this.addCateForm.cat_level = this.selectedKeys.length
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    // 点击添加分类对话框中的确定按钮监听的事件
    subAddCateForm() {
      // 预验证
      this.$refs.addCateForm.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post(
            'categories',
            this.addCateForm
          )
          if (res.meta.status !== 201) {
            return this.$message.error('添加分类失败')
          }
          this.getGoodsCate()
          this.addCateDialogVisible = false
          return this.$message.success('添加成功')
        } else {
          return ''
        }
      })
    },
    // 点击编辑按钮出现编辑对话框
    editCateName(goods) {
      this.editCateDialogVisible = true
      this.editCateForm = goods
    },
    // 关闭编辑对话框
    editCateDialogClose() {
      this.$refs.editCateForm.resetFields()
    },
    // 提交编辑表单
    subEditForm() {
      // 预验证
      this.$refs.editCateForm.validate(async valid => {
        if (!valid) return false
        this.editCateDialogVisible = false
        const { data: res } = await this.$http.put(
          `categories/${this.editCateForm.cat_id}`,
          {
            cat_name: this.editCateForm.cat_name
          }
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.getGoodsCate()
        return this.$message.success(res.meta.msg)
      })
    },
    // 删除分类
    deleteGoods(goods) {
      this.$confirm('此操作将永久删除该商品分类', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            'categories/' + goods.cat_id
          )
          if (res.meta.status !== 200) return this.$message.error('删除失败')
          this.getGoodsCate()
          return this.$message.success('删除成功')
        })
        .catch(() => {
          return this.$message.info('操作已取消')
        })
    }
  }
}
</script>

<style lang="less" scoped>
.margin {
  margin: 20px 0;
}
.success {
  color: #67c23a;
  font-size: 20px;
}
.error {
  color: #f56c6c;
  font-size: 20px;
}
.el-cascader {
  width: 100%;
}
</style>
